<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <div class="search">
      <el-form ref="search" :inline="true" :model="search">
        <!-- 点位搜索 -->
        <el-form-item label="点位搜索:" size="medium">
          <el-input v-model="search.name" clearable placeholder="请输入" />
        </el-form-item>
        <!-- 区域搜索 -->
        <el-form-item label="区域搜索:" size="medium">
          <el-select v-model="search.regionId" clearable placeholder="请选择">
            <el-option
              v-for="item in ereaList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-button
          type="primary"
          class="my-primary1"
          icon="el-icon-search"
          @click="getEreaDetail"
        >查询</el-button>
      </el-form>
    </div>

    <!-- 表单区域 -->
    <div class="result">
      <!-- 头部 -->
      <el-row class="operation">
        <el-button
          type="primary"
          class="my-primary2"
          icon="el-icon-circle-plus-outline"
          @click="addFormFn"
        >新建
        </el-button>
      </el-row>
      <!-- 表单主体 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column
          type="index"
          :index="(index) => (search.pageIndex - 1) * 10 + (index + 1)"
          label="序号"
          width="80"
        />
        <el-table-column prop="name" label="点位名称" />
        <el-table-column prop="region.name" label="所在区域" />
        <el-table-column prop="businessType.name" label="商圈类型" />
        <el-table-column prop="ownerName" label="合作商" />
        <el-table-column prop="addr" width="200" label="详细地址" />
        <el-table-column label="操作" width="200">
          <template v-slot="{ row }">
            <el-button
              type="text"
              class="el-button--primary-text"
              @click="showDetailDialog(row.id)"
            >
              查看详情
            </el-button>
            <el-button
              type="text"
              class="el-button--primary-text"
              @click="modifyNode(row.id)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              class="el-button--primary-text del-color"
              @click="delNode(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表单底部 -->
      <div class="pagination-container">
        <el-pagination
          layout="slot,prev,next"
          :current-page.sync="search.pageIndex"
          prev-text="上一页"
          next-text="下一页"
          background
          :total="totalCount"
          :page-size="search.pageSize"
          @current-change="getEreaDetail"
        >
          <template order="-1">
            <span
              class="el-pagination__total"
            >共{{ totalCount }}条记录 第 {{ search.pageIndex }}/{{
              totalPage
            }}
              页</span>
          </template>
        </el-pagination>
      </div>
    </div>
    <!-- 新增点位弹窗 -->
    <el-dialog
      :title="`${currentId ? '修改' : '新增'}点位`"
      :visible.sync="addFormDialog"
      width="630px"
      @close="closeFn"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item label="点位名称：" prop="name">
          <el-input
            v-model="addForm.name"
            autocomplete="off"
            placeholder="请输入"
            style="width: 396px"
            show-word-limit
            maxlength="15"
          />
        </el-form-item>
        <el-form-item label="所在区域：" prop="regionId">
          <el-select
            v-model="addForm.regionId"
            style="width: 396px"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in ereaList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属商圈：" prop="businessId">
          <el-select
            v-model="addForm.businessId"
            style="width: 396px"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in businessType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="归属合作商：" prop="ownerId">
          <el-select
            v-model="addForm.ownerId"
            style="width: 396px"
            clearable
            placeholder="请选择"
            @change="ownerChange"
          >
            <el-option
              v-for="item in partner"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址：" prop="areaCode">
          <el-cascader
            v-model="addForm.areaCode"
            :options="options"
            style="width: 396px"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item prop="addr">
          <el-input
            v-model="addForm.addr"
            maxlength="60"
            show-word-limit
            style="width: 396px"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <div class="dialog-footer">
          <el-row type="flex" align="middle" justify="center">
            <el-col style="text-align: center">
              <el-button
                class="my-secondary"
                @click="addFormDialog = false"
              >取 消</el-button>
              <el-button
                type="primary"
                class="my-primary2"
                style="margin-left: 34px"
                @click="saveData"
              >确 定</el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog title="点位详情" :visible.sync="nodeDetailDialog" width="630px">
      <el-form>
        <el-form-item>
          <el-table
            :data="nodeDetailList"
            style="width: 100%"
            empty-text="暂无数据"
            fit
            highlight-current-row
            :cell-style="{
              height: '44px',
              padding: '2px 0px',
              textAlign: 'left',
              color: 'rgb(102, 102, 102)',
              borderBottom: 'none',
            }"
            :header-cell-style="{
              lineHeight: 1.15,
              padding: '10px 0px 9px',
              background: 'rgb(243, 246, 251)',
              fontWeight: 500,
              textAlign: 'left',
              color: 'rgb(102, 102, 102)',
              borderBottom: 'none',
            }"
          >
            <el-table-column
              type="index"
              :index="(index) => index + 1"
              label="序号"
              width="80px"
            />
            <el-table-column prop="innerCode" label="机器编号" />
            <el-table-column prop="vmStatus" label="设备状态" />
            <el-table-column prop="lastSupplyTime" label="最后一次供货时间" />
          </el-table>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getDataByTree } from '@/utils'
import { regionData } from 'element-china-area-data'
import { getPartnerList } from '@/api/partner'
import {
  getEreaList,
  getEreaDetail,
  delNode,
  getBusinessType,
  addNode,
  modifyNode,
  getNodeDetail
} from '@/api/vm'
import store from '@/store'
import moment from 'moment'
export default {
  name: 'EreaManageContainer',
  data() {
    return {
      search: {
        pageIndex: 1,
        pageSize: 10,
        name: '',
        regionId: null
      },
      options: regionData,
      addFormDialog: false,
      nodeDetailDialog: false,
      addForm: {
        name: '',
        addr: '',
        areaCode: '',
        createUserId: store.getters.userId,
        regionId: '',
        businessId: '',
        ownerId: '',
        ownerName: ''
      },
      addrDetail: '',
      partner: [],
      businessType: [],
      nodeDetailList: [],
      tableData: [],
      totalPage: 0,
      totalCount: 0,
      ereaList: [],
      currentId: null,
      currentName: '',
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        addr: [{ required: true, message: '请输入', trigger: 'change' }],
        areaCode: [{ required: true, message: '请输入', trigger: 'change' }],
        regionId: [{ required: true, message: '请输入', trigger: 'change' }],
        businessId: [{ required: true, message: '请输入', trigger: 'change' }],
        ownerId: [{ required: true, message: '请输入', trigger: 'change' }],
        ownerName: [{ required: true, message: '请输入', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getEreaList()
    this.getEreaDetail()
  },
  methods: {
    closeFn() {
      this.addForm = {
        name: '',
        addr: '',
        areaCode: '',
        createUserId: store.getters.userId,
        regionId: '',
        businessId: '',
        ownerId: '',
        ownerName: ''
      }
      this.$refs.addForm.resetFields()
      this.addFormDialog = false
    },
    async addFormFn() {
      this.addFormDialog = true
      const { currentPageRecords } = await getPartnerList({ ...this.search })
      this.partner = currentPageRecords
      this.businessType = await getBusinessType()
    },
    ownerChange() {
      this.addForm.ownerName = this.partner.find(
        (item) => item.id === this.addForm.ownerId
      ).name
    },
    handleChange(val) {
      this.addForm.areaCode = val.at(-1)
      this.addrDetail = getDataByTree(this.options, val).join('-')
      // this.addForm.addr =
      //   getDataByTree(this.options, val).join('-') + '-' + this.addForm.addr
      console.log(this.addForm.addr)
      console.log(this.addrDetail)
    },
    async getEreaDetail() {
      const res = await getEreaDetail({ ...this.search })
      this.totalCount = +res.totalCount
      this.totalPage = +res.totalPage
      this.tableData = res.currentPageRecords.map((item) => {
        item.addr = item.addr.split('-').at(-1)
        return item
      })
    },
    async showDetailDialog(id) {
      this.nodeDetailList = (await getNodeDetail(id)).map((item) => {
        item.vmStatus =
          item.vmStatus === 0
            ? '未投放'
            : item.vmStatus === 1
              ? '运营'
              : item.vmStatus === 3
                ? '撤机'
                : '无'
        item.lastSupplyTime = moment(item.lastSupplyTime).format('YYYY.MM.DD HH:mm:ss')
        return item
      })
      console.log(this.nodeDetailList)
      this.nodeDetailDialog = true
    },
    async delNode(id) {
      await delNode(id)
      this.$message.success('点位删除成功')
      this.getEreaDetail()
    },
    async modifyNode(id) {
      this.currentId = id
      const { currentPageRecords } = await getEreaDetail()
      const res = currentPageRecords.find((item) => item.id === id)
      console.log(res)
      const req = await getPartnerList({ ...this.search })
      this.partner = req.currentPageRecords
      this.businessType = await getBusinessType()
      this.addForm.name = res.name
      this.addForm.addr = res.addr.split('-').at(-1)
      this.addForm.areaCode = res.areaCode
      this.addForm.regionId = res.regionId
      this.addForm.businessId = res.businessId
      this.addForm.ownerId = res.ownerId
      this.addForm.ownerName = res.ownerName
      this.addFormDialog = true
    },
    // 区域搜索
    async getEreaList() {
      const res = await getEreaList({ ...this.search })
      // console.log(res)
      this.ereaList = res.currentPageRecords
    },
    async saveData() {
      this.$refs.addForm.validate(async(pass) => {
        if (!pass) return
        this.addForm.addr = this.addrDetail + '-' + this.addForm.addr
        this.currentId
          ? await modifyNode({ ...this.addForm, id: this.currentId })
          : await addNode({ ...this.addForm })
        this.addFormDialog = false
        this.$message.success(`${this.currentId ? '编辑' : '新增'}成功`)
        this.getEreaDetail()
        this.closeFn()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/common.scss";
.search .el-form-item {
  margin-bottom: 0;
}

::v-deep .el-form-item__label {
  font-weight: normal;
}

.taskDetail .el-form-item {
  margin-bottom: 0;
}
</style>
